<template>

    <van-nav-bar title="信息编辑" left-text="返回" left-arrow @click-left="onClickLeft" />

    <van-form @submit="onSubmit" @failed="onFailed">
        <div class="cover">
            <van-uploader width="100" height="100" fit="cover" position="contain top" :before-read="beforeRead"
                :after-read="afterRead" v-model="fileList" multiple :max-count="1" :max-size="500 * 1024"
                @oversize="onOversize" />
            <!-- :show-upload="isShowUpload" :deletable="false" -->
        </div>

        <van-cell-group inset>
            <div style="margin-top:15px;">
            <van-field required v-model="user.username" name="用户名" label="用户名" placeholder="用户名"
                :rules="[{ required: true, message: '请填写真实姓名' }]" />
                </div>
                <div style="margin-top:5px;">
            <van-field v-model="user.gender" type="gender" name="性别" label="性别" placeholder="性别"
                :rules="[{ required: true, message: '请填写性别' }]" />
            </div>
            <div style="margin-top:5px;">
            <van-field v-model="user.password" type="password" name="密码" label="密码" placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]" />
            </div>
            <div style="margin-top:5px;">
            <van-field v-model="user.userBirthday" name="生日" label="生日" placeholder="生日"
                :rules="[{ required: true, message: '请完善个人信息~' }]" />
</div>

            <!-- 手机号 -->
            <div style="margin-top:5px;">
            <van-field
        required
        v-model="user.userTel"
        type="tel"
        label="手机号"
        :rules="[
          { required: true, message: '请填手机号！' },
          { validator: isMobile, message: '手机号格式不正确！' },
        ]"
      /></div>
            <!-- 邮箱 -->
            <div style="margin-top:5px;">
            <van-field
        v-model="user.userEmail"
        type="mail"
        label="邮箱"
        value="default@example.com"
        :rules="[
          { required: true, message: '请完善邮箱信息！' },
          { validator: validEmail, message: '邮箱格式不正确！' },
        ]"
      /></div>
            <!-- 地址选择 -->
            <div style="margin-top:5px;">
            <van-field v-model="districtName" is-link readonly label="选择省市区" placeholder="选择省市区"
                @click="showDistrictPicker = true" />
            <van-popup v-model:show="showDistrictPicker" round position="bottom">
                <van-area  title="选择省市区" :area-list="areaList" :value="user.userDistrict" @confirm="onDistrictConfirm"
                    @cancel="showDistrictPicker = false" />
            </van-popup>

            <van-field required v-model="user.userAddress" label="详细地址" placeholder="详细地址" />
            </div>
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit" color="linear-gradient(to right, #ff6034, #ee0a24)">
                &nbsp;提&nbsp;交&nbsp;
            </van-button>
        </div>
    </van-form>
</template>

<script setup>
import http from '@/utils/request.js'
import { ref, reactive, onBeforeMount } from 'vue';
import { Notify,Toast } from 'vant';
import { areaList } from '@vant/area-data';
import { computed } from '@vue/reactivity';
import { isMobile,validEmail} from "@/utils/validate.js";
const props = defineProps(['id'])
const onClickLeft = () => history.back();
const showDistrictPicker = ref(false);
const fileList = ref([
]);
const onOversize = (file) => {
    console.log(file);
    Toast('文件大小不能超过 500kb');
};
// 返回布尔值
const beforeRead = (file) => {
    if (file.type !== 'image/jpeg') {
        Toast('请上传 jpg 格式图片');
        return false;
    }
    return true;
};

// 返回 Promise
const asyncBeforeRead = (file) => {
    return new Promise((resolve, reject) => {
        if (file.type !== 'image/jpeg') {
            Toast('请上传 jpg 格式图片');
            reject();
        } else {
            const img = new File(['foo'], 'bar.jpg', {
                type: 'image/jpeg',
            });
            resolve(img);
        }
    });
};

//用户详细信息
const user = reactive({
    username: '',
    password: '',
    gender: '',
    userBirthday: '',

    userId: props.id, userName: '', userGender: '',
    userTel:'',userEmail:'',
    userBirthday: '', userDistrict: '',
    userProvince: '',
    userProvinceName: '',
    userCity: '',
    userCityName: '',
    userDistrict: '',
    userDistrictName: '',
    userAddress: ''
});
// 地址选择
//确认选择省市区触发的事件
const onDistrictConfirm = function (areaValues) {
    console.log('onDistrictConfirm = ', areaValues);
    showDistrictPicker.value = false;
    user.userProvince = areaValues[0].code;
    user.userProvinceName = areaValues[0].name;
    user.userCity = areaValues[1].code;
    user.userCityName = areaValues[1].name;
    user.userDistrict = areaValues[2].code;
    user.userDistrictName = areaValues[2].name;
    console.log(user);
}
//当用户选择省市区之后，显示 省/市/区
const districtName = computed(() => {
    if (user.userDistrictName) {
        return user.userProvinceName + '/' + user.userCityName + '/' + user.userDistrictName;
    } else {
        return '请选择 省/市/区';
    }
})

// const onSubmit = (values) => {
//   console.log('submit', values);
// };

//提交表单（校验通过后会执行，需要大家实现表单的校验）
const onSubmit = function () {
    console.log("待修改的用户信息：", user);
    if (user.userId && user.userId > 0) { //修改用户信息
        http.put(
            '/user',
            user
        ).then((res) => {
            if (res.data.resCode === '200') {
                Notify({ type: 'success', message: '修改成功！' })
                setTimeout(() => {
                    history.back();
                }, 500);
            }
        })
    }
};
</script>
 
<style scoped lang="scss">
@import "../style/mixins.scss";
@import "../style/viriables.scss";

.cover {
    background-color: rgb(255, 208, 0);
    padding: 50px;
    text-align: center;
}
</style>